<template>
  <el-card shadow="hover">
    <!-- 按钮 -->
    <el-button
      type="primary"
      size="default"
      style="margin: 10px 0"
      :icon="Plus"
      @click="addTradeMark"
      v-visite="'btn.Trademark.add'"
      >添加</el-button
    >
    <!-- 表格 -->
    <el-table border style="width: 100%" :data="markObj.records">
      <el-table-column prop="id" label="序号" width="80px" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <a :title="row.tmName">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 60px; border-radius: 10px"
            />
          </a>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #="{ row, $index }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="updateTradeMark(row)"
          ></el-button>
          <el-button
           type="danger" 
           size="small"
            :icon="Delete"
            @confirm="handler(row)"
            ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分液器 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="markObj.total"
      :page-sizes="[3, 5, 7]"
      background
      :pager-count="7"
      layout="prev, pager, next, jumper,->,sizes,total"
      @current-change="getTradeMarkList"
      @size-change="sizeHandler"
    />
    <!-- 添加修改品牌对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="tmParams.id ?'修改品牌' :'添加品牌'" draggable>
      <el-form
        style="width: 80%"
        :model="tmParams"
        :rules="rules"
        ref="formRef"
      >
        <!--收集品牌名称地方-->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="tmParams.tmName" />
        </el-form-item>
        <!--收集品牌lOGO地方-->
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="tmParams.logoUrl"
              :src="tmParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addUpData">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
//图片上传类型
import type { UploadProps, FormInstance } from "element-plus";
//消息提示框
import { ElMessage } from "element-plus";
//品牌管理列表数据
import {
  reqTrademarkList,
  reqUpdataTrademark,
  reqDeleteTrademark
} from "@/api/product/trademark/trademark";
//返回数据类型
import type {
  trademarkResponseData,
  trademark,
} from "@/api/product/trademark/model/trademark";
import { onMounted, reactive, ref } from "vue";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Plus,
} from "@element-plus/icons-vue";


//方法
//保存分页器当前页码[当前第几页]
const currentPage = ref<number>(1);
//保存当前页面显示几条数据
const pageSize = ref<number>(3);
//loading响应效果
let loading = ref<boolean>(false);
//图片按钮的显示和隐藏
let dialogFormVisible = ref<boolean>(false);
//存储组件实例el-form
let formRef = ref<FormInstance>();
//收集新增品牌数据
let tmParams = reactive<trademark>({
  logoUrl: "",
  tmName: "",
});
//定义接受服务器返回的品牌数据:total|records
let markObj = reactive<trademarkResponseData>({
  total: 0,
  records: [],
});
//专门获取品牌数据的函数
const getTradeMarkList = async (page: number = 1) => {
  loading.value = true;
  currentPage.value = page;
  let result = await reqTrademarkList(currentPage.value, pageSize.value);
  markObj.total = result.total;
  markObj.records = result.records;
  loading.value = false;
};
//右边下拉菜单修改一页展示几条数据的回调
const sizeHandler = (limit: number) => {
  pageSize.value = limit;
  getTradeMarkList();
};
onMounted(() => {
  getTradeMarkList();
});

//上传图片成功的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  tmParams.logoUrl = response.data;
};
//判断上传图片状态
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/svg"
  ) {
    if (rawFile.size / 1024 / 1024 < 5) {
      ElMessage.success("图片上传成功");
      return;
    }
  } else {
    ElMessage.error("图片上传是失败");
    return false;
  }
};
//点击上传图片确定按钮提交数据
const addUpData = async () => {
  //全部字段校验
  formRef.value?.validate(async (success) => {
    if (success) {
      //提交数据
      await reqUpdataTrademark(tmParams);
      //对话框关闭
      dialogFormVisible.value = false;
      //再次获取最新的全部品牌的数据
      getTradeMarkList(tmParams.id ? currentPage.value : 1);
      ElMessage({
          type:'success',
          message:tmParams.id?'修改品牌成功':'添加品牌成功'
      })
    } else {
      ElMessage({
        type: "warning",
        message: "大哥你看点规则,别瞎搞",
        duration:500//提示消息时间的设置
      });
    }
  });
};


//添加按钮的回调
const addTradeMark = () => {
  //对话框显示出来
  dialogFormVisible.value = true;
  tmParams.id = "";
  tmParams.tmName = "";
  tmParams.logoUrl = "";
};
//修改按钮的回调
const updateTradeMark = (row: trademark) => {
  nextTick(()=>{
  formRef.value?.resetFields();
  //对话框显示出来
  dialogFormVisible.value = true;
  tmParams.id = row.id;
  tmParams.tmName = row.tmName;
  tmParams.logoUrl = row.logoUrl;
})
  
};
//自定义校验规则
const validatetmName=(rule: any, value: any, next: any)=>{
  if (value.length > 2) {
    next();
  } else {
    next(new Error("品牌名字大于2"));
  }
}
//表单验证
const rules = reactive({
  tmName: [
    
    { min: 2, max: 10,  validator: validatetmName },
  ],
  logoUrl: [{ required: true, message: "请你上传logo图片" }],
});
//删除某一个品牌数据
const handler= async (row:trademark)=>{
try {
  await reqDeleteTrademark(row.id)
   //提示信息
   ElMessage({
      type: "success",
      message: `删除${row.tmName}成功`,
    });
    //再次获取最新数据
    getTradeMarkList(currentPage.value);
} catch (error) {
  
}
}
</script>

<style scoped>
/**上传照片的样式**/
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
  
  <style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>